<script setup lang="ts">
import { ref, onMounted } from "vue";
import { message } from "ant-design-vue";
import { AccountBookOutlined } from "@ant-design/icons-vue";
import {
  listPaymentBillByPage,
  addPaymentBill,
  updatePaymentBill,
  deletePaymentBill,
} from "@/api/paymentBill";
import type {
  PaymentBill,
  PaymentBillQueryRequest,
  PaymentBillAddRequest,
  PaymentBillUpdateRequest,
} from "@/models/paymentBill";
import dayjs from "dayjs";

// 支付方式选项
const paymentMethods = [
  { value: "微信", label: "微信" },
  { value: "支付宝", label: "支付宝" },
  { value: "现金", label: "现金" },
];

// 缴费用途选项
const paymentPurposes = [
  { value: "水费", label: "水费" },
  { value: "电费", label: "电费" },
  { value: "水电费", label: "水电费" },
];

// 缴费记录管理相关状态
const bills = ref<PaymentBill[]>([]);
const billTotal = ref(0);
const billCurrentPage = ref(1);
const billPageSize = ref(6);
const userIdSearch = ref("");
const dormitoryIdSearch = ref("");
const billLoading = ref(false);

// 排序信息
const sortInfo = ref({
  sortField: undefined as string | undefined,
  sortOrder: undefined as string | undefined,
});

// 缴费记录编辑弹窗
const billModalVisible = ref(false);
const billModalTitle = ref("添加缴费记录");
const editingBill = ref<PaymentBillUpdateRequest>({
  paymentId: 0,
  userId: "",
  dormitoryId: 0,
  billId: 0,
  paymentDate: "",
  paymentAmount: 0,
  paymentMethod: "微信",
  paymentPurpose: "水电费",
});

// 获取缴费记录列表
const fetchBills = async () => {
  billLoading.value = true;
  try {
    const queryRequest: PaymentBillQueryRequest = {
      current: billCurrentPage.value,
      pageSize: billPageSize.value,
      userId: userIdSearch.value || undefined,
      dormitoryId: dormitoryIdSearch.value
        ? parseInt(dormitoryIdSearch.value)
        : undefined,
      sortField: sortInfo.value.sortField,
      sortOrder: sortInfo.value.sortOrder,
    };
    const res = await listPaymentBillByPage(queryRequest);
    if (res.data.code === 0) {
      bills.value = res.data.data.records;
      billTotal.value = res.data.data.total;
    } else {
      message.error("获取缴费记录列表失败");
    }
  } catch (error) {
    message.error("获取缴费记录列表失败");
  } finally {
    billLoading.value = false;
  }
};

// 搜索缴费记录
const onSearch = () => {
  billCurrentPage.value = 1;
  fetchBills();
};

// 重置搜索和排序
const handleReset = () => {
  userIdSearch.value = "";
  dormitoryIdSearch.value = "";
  billCurrentPage.value = 1;
  sortInfo.value.sortField = undefined;
  sortInfo.value.sortOrder = undefined;
  fetchBills();
};

// 处理表格变化（包括分页和排序）
const handleTableChange = (pagination: any, filters: any, sorter: any) => {
  billCurrentPage.value = pagination.current;
  billPageSize.value = pagination.pageSize;

  // 处理排序
  if (sorter.field) {
    sortInfo.value.sortField = sorter.field;
    sortInfo.value.sortOrder = sorter.order === "ascend" ? "asc" : "desc";
  } else {
    sortInfo.value.sortField = undefined;
    sortInfo.value.sortOrder = undefined;
  }

  fetchBills();
};

// 添加缴费记录
const handleAddBill = () => {
  billModalTitle.value = "添加缴费记录";
  editingBill.value = {
    paymentId: 0,
    userId: "",
    dormitoryId: 0,
    billId: 0,
    paymentDate: "",
    paymentAmount: 0,
    paymentMethod: "微信",
    paymentPurpose: "水电费",
  };
  billModalVisible.value = true;
};

// 编辑缴费记录
const handleEditBill = (record: PaymentBill) => {
  billModalTitle.value = "编辑缴费记录";
  editingBill.value = {
    ...record,
    paymentDate: dayjs(record.paymentDate).format("YYYY-MM-DD"),
  };
  billModalVisible.value = true;
};

// 删除缴费记录
const handleDeleteBill = async (record: PaymentBill) => {
  try {
    const res = await deletePaymentBill(record.paymentId);
    if (res.data.code === 0) {
      message.success("删除成功");
      fetchBills();
    } else {
      message.error(res.data.message || "删除失败");
    }
  } catch (error) {
    message.error("删除失败");
  }
};

// 保存缴费记录
const handleSaveBill = async () => {
  try {
    if (!editingBill.value.userId || !editingBill.value.paymentDate) {
      message.error("请填写完整信息");
      return;
    }

    if (editingBill.value.paymentId === 0) {
      // 添加缴费记录
      const res = await addPaymentBill(editingBill.value);
      if (res.data.code === 0) {
        message.success("添加成功");
      } else {
        message.error(res.data.message || "添加失败");
      }
    } else {
      // 更新缴费记录
      const res = await updatePaymentBill(editingBill.value);
      if (res.data.code === 0) {
        message.success("更新成功");
      } else {
        message.error(res.data.message || "更新失败");
      }
    }
    billModalVisible.value = false;
    fetchBills();
  } catch (error) {
    message.error("操作失败");
  }
};

onMounted(() => {
  fetchBills();
});
</script>

<template>
  <a-card class="info-card">
    <template #title>
      <div class="card-title">
        <account-book-outlined />
        <span>历史缴费管理</span>
      </div>
    </template>

    <!-- 搜索区域 -->
    <template #extra>
      <a-space>
        <a-input
          v-model:value="userIdSearch"
          placeholder="用户ID"
          style="width: 150px"
          @pressEnter="onSearch"
        />
        <a-input
          v-model:value="dormitoryIdSearch"
          placeholder="宿舍ID"
          style="width: 150px"
          @pressEnter="onSearch"
        />
        <a-button type="primary" @click="onSearch">搜索</a-button>
        <a-button @click="handleReset">重置</a-button>
        <a-button type="primary" @click="handleAddBill">
          添加缴费记录
        </a-button>
      </a-space>
    </template>

    <!-- 表格区域 -->
    <a-table
      :dataSource="bills"
      :loading="billLoading"
      :pagination="{
        total: billTotal,
        current: billCurrentPage,
        pageSize: billPageSize,
        showSizeChanger: true,
        showQuickJumper: true,
      }"
      @change="handleTableChange"
    >
      <a-table-column key="paymentId" title="缴费ID" data-index="paymentId" />
      <a-table-column key="userId" title="用户ID" data-index="userId" />
      <a-table-column
        key="dormitoryId"
        title="宿舍ID"
        data-index="dormitoryId"
      />
      <a-table-column
        key="paymentDate"
        title="缴费日期"
        data-index="paymentDate"
        :sorter="true"
        :customRender="({ text }) => dayjs(text).format('YYYY-MM-DD')"
      />
      <a-table-column
        key="paymentAmount"
        title="缴费金额"
        data-index="paymentAmount"
        :customRender="({ text }) => `￥${text.toFixed(2)}`"
      />
      <a-table-column
        key="paymentMethod"
        title="缴费方式"
        data-index="paymentMethod"
      />
      <a-table-column
        key="paymentPurpose"
        title="缴费用途"
        data-index="paymentPurpose"
      />
      <a-table-column
        key="createTime"
        title="创建时间"
        data-index="createTime"
        :customRender="({ text }) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')"
      />
      <a-table-column key="action" title="操作">
        <template #default="{ record }">
          <a-space>
            <a-button type="link" @click="handleEditBill(record)"
              >编辑</a-button
            >
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除这条记录吗？"
              @confirm="handleDeleteBill(record)"
            >
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table-column>
    </a-table>

    <!-- 编辑弹窗 -->
    <a-modal
      v-model:visible="billModalVisible"
      :title="billModalTitle"
      @ok="handleSaveBill"
    >
      <a-form :model="editingBill" layout="vertical">
        <a-form-item label="用户ID" required>
          <a-input v-model:value="editingBill.userId" />
        </a-form-item>
        <a-form-item label="宿舍ID" required>
          <a-input-number
            v-model:value="editingBill.dormitoryId"
            style="width: 100%"
            :min="1"
          />
        </a-form-item>
        <a-form-item label="账单ID" required>
          <a-input-number
            v-model:value="editingBill.billId"
            style="width: 100%"
            :min="1"
          />
        </a-form-item>
        <a-form-item label="缴费日期" required>
          <a-date-picker
            v-model:value="editingBill.paymentDate"
            style="width: 100%"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
          />
        </a-form-item>
        <a-form-item label="缴费金额" required>
          <a-input-number
            v-model:value="editingBill.paymentAmount"
            style="width: 100%"
            :min="0"
            :step="0.01"
            prefix="￥"
          />
        </a-form-item>
        <a-form-item label="缴费方式" required>
          <a-select v-model:value="editingBill.paymentMethod">
            <a-select-option
              v-for="method in paymentMethods"
              :key="method.value"
              :value="method.value"
            >
              {{ method.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="缴费用途" required>
          <a-select v-model:value="editingBill.paymentPurpose">
            <a-select-option
              v-for="purpose in paymentPurposes"
              :key="purpose.value"
              :value="purpose.value"
            >
              {{ purpose.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<style scoped>
.info-card {
  margin-bottom: 24px;
}

.card-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  color: #1f1f1f;
}

.card-title .anticon {
  margin-right: 12px;
  font-size: 20px;
  color: #1890ff;
}
</style>
